<?php

namespace app\proxyapi\controller;

use app\proxyapi\service\ProxyTokenService;
use think\admin\Controller;

class BaseProxyController extends Controller
{
    protected function checkTokenReturnUserId(): int
    {
        $result = $this->checkToken();
        return $result[2];
    }

    protected function checkToken(): array
    {
        $token = $this->getTokenString();
        // 检查token
        if (empty($token)) $this->error("token 已过期！",'',-500);
        $result = ProxyTokenService::instance()->check($token);
        if ($result[0] != 1) $this->error($result[1],'',-500);

        return $result;
    }

    protected function getTokenString()
    {
        $header = $this->request->header();
        if (isset($header['token']) && !empty($header['token'])) {
            return $header['token'];
        }
        $get = $this->request->get();
        if (isset($get['token']) && !empty($get['token'])) {
            return $get['token'];
        }
        $post = $this->request->post();
        if (isset($post['token']) && !empty($post['token'])) {
            return $post['token'];
        }
        return null;
    }

    protected function trimStr($value): ?string
    {
        if ($value && trim($value)) {
            return trim($value);
        }

        return null;
    }
}